package com.fengxu.gamescript.ui.setting

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import androidx.core.widget.doOnTextChanged
import com.fengxu.gamescript.R
import com.fengxu.gamescript.boot.KeySetBoot
import com.fengxu.gamescript.data.other.KeyConfData
import com.fengxu.gamescript.data.other.Point
import com.fengxu.gamescript.ui.article.ArticleActivity
import com.xuexiang.xui.widget.button.roundbutton.RoundButton
import com.xuexiang.xui.widget.button.switchbutton.SwitchButton
import com.xuexiang.xui.widget.edittext.materialedittext.MaterialEditText
import com.xuexiang.xui.widget.toast.XToast
import org.jetbrains.anko.sdk27.coroutines.onClick
import org.jetbrains.anko.sdk27.coroutines.textChangedListener
import org.jetbrains.anko.textColor
import java.lang.IllegalStateException
import java.util.*
import kotlin.properties.Delegates

/**
 * 键位设置的弹窗布局View
 */
class KeySetDialogView(ctx:Context) : FrameLayout(ctx) {

    // 配置名组件
    private val keySetNameView:MaterialEditText by lazy {
        findViewById(R.id.dialog_keyset_name)
    }

    // 配置名
    val keySetName:String
        get() = keySetNameView.text.toString()

    // 配置行列组件
    private val keyRectView:MaterialEditText by lazy {
        findViewById(R.id.dialog_keyset_rect)
    }

    // 行列配置，例3x7
    val keyRect:String
        get() = keyRectView.text.toString()

    // 键位行数
    val keyRow:Int
        get() = keyRect.split('x').first().toInt()

    // 键位列数
    val keyColumn:Int
        get() = keyRect.split('x').last().toInt()

    // 键位是否连续的开关组件
    private val keyIsSeriesSwitch: SwitchButton by lazy{
        findViewById(R.id.dialog_keyset_isSeries)
    }

    // 键位是否连续
    val keyIsSeries:Boolean
        get() = keyIsSeriesSwitch.isChecked

    // 高音是否降调的开关组件
    private val isAbateHighSwitch:SwitchButton by lazy{
        findViewById(R.id.dialog_keyset_isAbateHight)
    }

    // 高音是否降调
    val isAbateHigh:Boolean
        get() = isAbateHighSwitch.isChecked

    // 开始引导组件
    private val startBootView:RoundButton by lazy {
        findViewById(R.id.dialog_keyset_startKeyBoot)
    }

    // 是否进行了引导设置键位,为true时，修改提示
     var isBootSeted = false
        private set(value) {
            if(value){
                findViewById<TextView>(R.id.dialog_keyset_isBootSeted).run {
                    text = "已经进行引导设置"
                    textColor = Color.parseColor("#66CC99")
                }
            }else{
                findViewById<TextView>(R.id.dialog_keyset_isBootSeted).run {
                    text = "需要进行引导设置"
                    textColor = Color.RED
                }
            }
            field = value
        }

    // 用户设置的键位数组
    var keyPoints: Array<Point> by Delegates.notNull()
        private set

    init {
        LayoutInflater.from(ctx).inflate(R.layout.dialog_keyset,this)
        // 添加跳转文章事件
        findViewById<View>(R.id.dialog_keyset_startArticle).onClick {
            val intent = Intent(ctx, ArticleActivity::class.java)
            intent.putExtra("id","61a07e0c84dbb060592e334d")
            ctx.startActivity(intent)
        }
        // 监听用户改变行列设置后需要重新引导
        keyRectView.doOnTextChanged { _, _, _, _ -> isBootSeted = false }
        // 设置开始引导事件
        startBootView.onClick {
            startKeyBoot()
        }
    }

    /**
     * 初始化悬浮窗，初始值从KeyConfData对象上获取
     */
    fun initFromKeyConfData(keyConfData: KeyConfData){
        keySetNameView.setText(keyConfData.name)
        keyRectView.setText("${keyConfData.row}x${keyConfData.column}")
        keyIsSeriesSwitch.isChecked = keyConfData.isSeries
        isAbateHighSwitch.isChecked = keyConfData.isAbateHighVolume
        keyPoints = keyConfData.points
        isBootSeted = true
    }

    /**
     * 开始进行引导设置
     */
    private fun startKeyBoot() {
        // 验证是否通过配置名和配置行列
        if(!keySetNameView.validate() || !keyRectView.validate()){
            XToast.warning(context,"数据格式不正确!").show()
            return
        }
        // 开始键键位引导
        KeySetBoot(context).run {
            keyBootNumber = keyRow * keyColumn
            keyBootComplete = {
                // 引导完成后更新提示信息，并设置键位
                keyPoints = it
                isBootSeted = true
            }
            showBoot()
        }
    }

    /**
     * 验证用户是否已经完成所有流程设置
     */
    fun validate():Boolean{
        // 验证配置名和行列矩阵
        if(!keySetNameView.validate() || !keyRectView.validate()){
            return false
        }
        // 验证是否已经进行了键位设置
        return isBootSeted
    }

    /**
     * 获取完成后的键位配置
     */
    fun getKeyConfDataIfComplete():KeyConfData{
        if(!validate()){
            throw IllegalStateException("用户还未完成所有配置项!")
        }
        return KeyConfData().apply {
            name = keySetName
            row = keyRow
            column = keyColumn
            isSeries = keyIsSeries
            isAbateHighVolume = isAbateHigh
            createTime = Date()
            points = keyPoints
        }
    }

}